package com.share.example.sbnfsj.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import javax.sql.DataSource;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

@Configuration
public class DataSourcePubConfig {

    @Bean(name = "pubDataSource")
    @ConfigurationProperties(prefix = "jdbc.pub")
    public DataSource setDataSource() {
        return new ComboPooledDataSource();
    }


    @Bean(name = "pubSessionFactory")
    public LocalSessionFactoryBean setSqlSessionFactory(@Qualifier("pubDataSource") DataSource dataSource) throws Exception {

        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        hibernateProperties.setProperty("hibernate.show_sql", "true");
        hibernateProperties.setProperty("hibernate.format_sql", "true");
        hibernateProperties.setProperty("hibernate.jdbc.fetch_size", "10");
        hibernateProperties.setProperty("hibernate.connection.pool_size", "3");
        hibernateProperties.setProperty("hibernate.jdbc.batch_size", "100");
        hibernateProperties.setProperty("hibernate.connecton.SetBigStringTryClob", "true");

        List<String> packeagList = new LinkedList<>();
        packeagList.add("com.szeport.domain.system");

        LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setHibernateProperties(hibernateProperties);
        bean.setPackagesToScan(packeagList.toArray(new String[1]));
        return bean;
    }

    @Bean(name = "hibernateTemplatePub")
    public HibernateTemplate setSqlSessionTemplate(@Qualifier("pubSessionFactory") SessionFactory sessionFactory) throws Exception {
        HibernateTemplate bean = new HibernateTemplate();
        bean.setSessionFactory(sessionFactory);
        bean.setFetchSize(10);
        return bean;
    }


    @Bean(name = "transactionManagerPub")
    public HibernateTransactionManager pubTransactionManager(@Qualifier("pubSessionFactory") SessionFactory sessionFactory) {
        return new HibernateTransactionManager(sessionFactory);
    }
}